package com.hmall.search.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.feign.client.ItemClient;
import com.hmall.feign.dto.Item;
import com.hmall.search.constants.ESConstants;
import com.hmall.search.document.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 更新、删除ES中的文档
 */
@Component
public class MqSyncEsService {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ItemClient itemClient;

    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest(ESConstants.ES_INDEX_NAME, id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void insertById(Long id) {
        try {
            Item item = itemClient.queryItemById(id);
            // 转换为文档类型
            ItemDoc doc = new ItemDoc(item);
            // 1.准备Request对象
            ObjectMapper objectMapper = new ObjectMapper();
            IndexRequest request = new IndexRequest(ESConstants.ES_INDEX_NAME).id(doc.getId().toString());
            // 2.准备Json文档
            request.source(objectMapper.writeValueAsString(doc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
